package atguigu.web;

import atguigu.pojo.Book;
import atguigu.pojo.Page;
import atguigu.service.BookService;
import atguigu.service.impl.BookServiceImpl;
import atguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientBookServlet extends BaseServlet{
    private BookService bookService = new BookServiceImpl();
    //处理分页功能
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求的参数 pageNo,PageSize  默认为首页1
        String pages = req.getParameter("pageNo");
        int pageNo = WebUtils.parseInt(pages,1);
        //默认为显示4条记录
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2.调用BookService.page(pageNo,pageSize)方法  Page对象
        Page<Book> page = bookService.page(pageNo,pageSize);
        //设置前台页面 分页的访问地址
        page.setUrl("client/bookServlet?action=page");
        //3.保存Page对象到Request域中
        req.setAttribute("page",page);
        //4.请求转发到pages/client/book_manager.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
    //实现价格搜索
    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求的参数 pageNo,PageSize  默认为首页1
        String pages = req.getParameter("pageNo");
        int pageNo = WebUtils.parseInt(pages,1);
        //默认为显示4条记录
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min  = WebUtils.parseInt(req.getParameter("min"),0);
        int max = WebUtils.parseInt(req.getParameter("max"),0);
        //2.调用BookService.page(pageNo,pageSize)方法  Page对象
        Page<Book> page = bookService.pageByPrice(pageNo,pageSize,min,max);
        StringBuilder sb = new StringBuilder("client/bookServlet?action=pageByPrice");
        //如果有最小价格的参数  追加到分页条的地址参数中
        if(req.getParameter("min") !=null){
            sb.append("&min=").append(req.getParameter("min"));
        }
        //如果有最大价格的参数  追加到分页条的地址参数中
        if(req.getParameter("max") !=null){
            sb.append("&max=").append(req.getParameter("max"));
        }
        //设置前台页面 分页的访问地址
        page.setUrl(sb.toString());
        //3.保存Page对象到Request域中
        req.setAttribute("page",page);
        //4.请求转发到pages/client/book_manager.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }

}
